﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;
using System.Windows.Forms;
using System.IO;
using System.IO.Compression;
using Newtonsoft.Json;
using System.Drawing;
using HtmlAgilityPack;
using AutoBuyWinform.entity;

namespace AutoBuyWinform
{
    class Util
    {
        public static bool isEmpty(string str)
        {
            if (str == null || "".Equals(str.Trim()))
                return true;
            else
                return false;
        }

        //用于实现CookieContainer的复制操作
        public static CookieContainer GetCookieContainerCopy(CookieContainer cc)
        {
            CookieContainer newCC = new CookieContainer();
            newCC.Capacity = cc.Capacity;
            newCC.MaxCookieSize = cc.MaxCookieSize;
            newCC.PerDomainCapacity = cc.PerDomainCapacity;
            newCC.Add(new Uri(Form1.webUrl), InitCookieCollection(cc.GetCookies(new Uri(Form1.webUrl))));

            return newCC;
        }


        public static CookieCollection InitCookieCollection(CookieCollection ccReturned)
        {
            ccReturned.Add(new Cookie("Hm_lpvt_89e7e2c61beefae75bd63883432c760a", "1366552029"));
            //ccReturned.Add(new Cookie("Hm_lvt_89e7e2c61beefae75bd63883432c760a", "1366442351,1366470053,1366520315,1366539392"));
            ////show cookie
            //StringBuilder sb = new StringBuilder();
            //foreach (Cookie cookieValue in ccReturned)
            //{
            //    sb.AppendLine("Cookie: " + cookieValue.ToString());
            //}
            //MessageBox.Show(sb.ToString());
            return ccReturned;
        }

        public static HttpWebRequest createRequest(string targetUrl, string data, string originUrl, string refererUrl, string method, string acceptType, CookieContainer ccEntered)
        {
            string csrftoken = "";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUrl);
            request.CookieContainer = new CookieContainer();

            byte[] postData = Encoding.UTF8.GetBytes(data);

            //赋值权限戳
            foreach (Cookie cookieValue in ccEntered.GetCookies(new Uri(Form1.webUrl)))
            {
                if ("csrftoken".Equals(cookieValue.Name))
                {
                    csrftoken = cookieValue.Value;
                }
                if ("sessionid".Equals(cookieValue.Name))
                {
                    //MessageBox.Show(cookieValue.Value);
                }
            }

            request.Method = method;
            request.ProtocolVersion = HttpVersion.Version11;


            request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31";
            request.Referer = refererUrl;
            //request.KeepAlive = true;
            var sp = request.ServicePoint;
            var prop = sp.GetType().GetProperty("HttpBehaviour", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            prop.SetValue(sp, (byte)0, null);

            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            //request.Headers.Add("Cache-Control", "max-age=0");

            request.CookieContainer = ccEntered;

            if ("POST".Equals(method))
            {
                request.Accept = acceptType;
                request.ContentLength = postData.Length;
                request.Headers.Add("Origin", originUrl);
                request.Headers.Add("X-CSRFToken", csrftoken);
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            }
            else
            {
                request.Accept = acceptType;
            }



            if ("POST".Equals(method))
            {
                Stream st = request.GetRequestStream();
                st.Write(postData, 0, postData.Length);
                st.Close();
            }

            request.AllowAutoRedirect = false;
            return request;
        }

        public static String getResponse(HttpWebRequest request, out CookieCollection ccReturned)
        {
            HttpWebResponse response = null;
            string htmlText = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                ccReturned = response.Cookies;


                Stream st2 = response.GetResponseStream();

                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    st2 = new GZipStream(st2, CompressionMode.Decompress, true);
                }



                StreamReader stReader = new StreamReader(st2, Encoding.UTF8);
                htmlText = stReader.ReadToEnd();

                stReader.Close();
                st2.Close();

                response.Close();
            }
            catch (Exception)
            {
                ccReturned = null;
                if (response != null)
                {
                    response.Close();
                }
                return null;
            }

            return htmlText;
        }

        //用于获取验证码图像的方法
        public static Stream GetCheckCodeImageStream(string imageAddress, CookieContainer ccEntered, out CookieCollection ccReturned)
        {
            HttpWebRequest request;
            HttpWebResponse response;

            request = (HttpWebRequest)HttpWebRequest.Create(imageAddress);

            request.Method = "GET";
            request.ProtocolVersion = HttpVersion.Version11;
            //request.Connection = "keep-alive";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2";
            request.Accept = "*/*";

            //request.Connection = "keep-alive";
            request.KeepAlive = true;
            //request.Headers.Add("Connection", "keep-alive"); 

            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");

            request.CookieContainer = ccEntered;

            request.AllowAutoRedirect = true;

            response = (HttpWebResponse)request.GetResponse();
            ccReturned = response.Cookies;

            return response.GetResponseStream();
        }

        //用于获取商品页面的方法
        public static string GetPage(string pageUrl, CookieContainer ccEntered, out CookieCollection ccReturned)
        {
            HttpWebRequest request;
            HttpWebResponse response;

            request = (HttpWebRequest)HttpWebRequest.Create(pageUrl);

            request.Method = "GET";
            request.ProtocolVersion = HttpVersion.Version11;
            //request.Connection = "keep-alive";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            //request.Connection = "keep-alive";
            request.KeepAlive = true;
            //request.Headers.Add("Connection", "keep-alive"); 

            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");

            request.CookieContainer = ccEntered;

            request.AllowAutoRedirect = true;

            try
            {
                request.Timeout = 5000;
                response = (HttpWebResponse)request.GetResponse();
                ccReturned = response.Cookies;
            }catch(WebException)
            {
                ccReturned = null;
                return "";
            }
            

            ////show cookie
            //StringBuilder sb = new StringBuilder();
            //foreach (Cookie cookieValue in request.CookieContainer.GetCookies(new Uri(Form1.webUrl)))
            //{
            //    sb.AppendLine("Cookie: " + cookieValue.ToString());
            //}
            //MessageBox.Show(sb.ToString());

            Stream st;
            st = response.GetResponseStream();

            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new GZipStream(st, CompressionMode.Decompress, true);
            }

            string htmlText;

            StreamReader stReader = new StreamReader(st, Encoding.UTF8);
            htmlText = stReader.ReadToEnd();

            stReader.Close();
            st.Close();

            response.Close();

            return htmlText;
        }


        //用于获取商品页面的方法
        public static string GetPage(string pageUrl)
        {
            HttpWebRequest request;
            HttpWebResponse response;

            request = (HttpWebRequest)HttpWebRequest.Create(pageUrl);

            request.Method = "GET";
            request.ProtocolVersion = HttpVersion.Version11;
            //request.Connection = "keep-alive";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            //request.Connection = "keep-alive";
            request.KeepAlive = true;
            //request.Headers.Add("Connection", "keep-alive"); 

            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");

            //request.CookieContainer = ccEntered;

            request.AllowAutoRedirect = true;

            try
            {
                request.Timeout = 5000;
                response = (HttpWebResponse)request.GetResponse();
                //ccReturned = response.Cookies;
            }
            catch (WebException)
            {
                //ccReturned = null;
                return "";
            }


            ////show cookie
            //StringBuilder sb = new StringBuilder();
            //foreach (Cookie cookieValue in request.CookieContainer.GetCookies(new Uri(Form1.webUrl)))
            //{
            //    sb.AppendLine("Cookie: " + cookieValue.ToString());
            //}
            //MessageBox.Show(sb.ToString());

            Stream st;
            st = response.GetResponseStream();

            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new GZipStream(st, CompressionMode.Decompress, true);
            }

            string htmlText;

            StreamReader stReader = new StreamReader(st, Encoding.UTF8);
            htmlText = stReader.ReadToEnd();

            stReader.Close();
            st.Close();

            response.Close();

            return htmlText;
        }

    }
}
